<?php
/**
 * 
 * 留言静态类
 * @author will
 *
 */
class Message {
	static public $message_id = 0;
	
	/**
	 * 获取总留言数
	 * @param <int> $uin
	 */
	static public function getCount($uin) {
		$Db = loadDB();
		
		$result = $Db->getOne("SELECT COUNT(*) AS `count` FROM `message` WHERE `uin` = {$uin}");

		return empty($result) ? 0 : $result['count'];
	}
	
	/**
	 * 获取留言列表
	 * @param <int> $uin
	 * @param <int> $offset
	 * @param <int> $limit
	 */
	static public function getList($uin , $offset = 0 , $limit = 10) {
		$Db = loadDB();
		
		$list = $Db->getAll("SELECT * FROM `message` WHERE `uin` = {$uin} ORDER BY `id` DESC LIMIT {$offset} , {$limit}");
		
		// 解析回复
		foreach($list as $k => $row) {
			$list[$k]['reply'] = empty($row['reply']) ? array() : unserialize($row['reply']);
		}

		return $list;
	}
	
	/**
	 * 获取单条留言
	 * @param <int> $uin
	 * @param <int> $id
	 */
	static public function getOne($uin , $id) {
		$Db = loadDB();
		
		$result = $Db->getOne("SELECT * FROM `message` WHERE `uin` = {$uin} AND `id` = {$id}");
		$result['reply'] = empty($result['reply']) ? array() : unserialize($result['reply']);

		return $result;
	}
	
	/**
	 * 发表留言
	 * @param <int> $uin
	 * @param <int> $send_uin
	 * @param <string> $content
	 */
	static public function add($uin , $send_uin , $content) {
		$Db = loadDB();
		
		$time = time();
		// 写入数据
		$insert_data = array(
			'uin' => $uin,
			'send_uin' => $send_uin,
			'content' => $content,
			'reply' => '',
			'time' => $time,
		);
		$success = $Db->doInsert('message' , $insert_data);
		
		if($success) {
			self::$message_id = $Db->getLastId();
		}
		
		return $success ? 0 : 401;
	}
	
	/**
	 * 回复留言
	 * @param <int> $uin
	 * @param <int> $send_uin
	 * @param <int> $id
	 * @param <string> $content
	 */
	static public function reply($uin , $send_uin , $id , $content , $org_message = false) {
		$Db = loadDB();
		
		// 取原数据
		if(empty($org_message)) {
			$message = self::getOne($uin , $id);
			if(empty($message)) {
				return 404;	// 该留言不存在
			}
		} else {
			$message = $org_message;
		}
		
		if(!in_array($send_uin , array($message['uin'] , $message['send_uin']))) {
			return 405;	// 只能主人与留言者直接相互回复
		}
		
		$time = time();
		$message['reply'][] = array('uin' => $send_uin , 'content' => $content , 'time' => $time);
		
		
		// 写入数据
		$update_data = array(
			'reply' => serialize($message['reply']),
		);
		$success = $Db->doUpdate('message' , $update_data , '`id` = ' . $id);
		
		return $success ? 0 : 403;
	}
	
	/**
	 * 删除留言
	 * @param <int> $uin
	 * @param <int> $id
	 */
	static public function delete($uin , $id) {
		$Db = loadDB();
		
		// 写入数据
		$success = $Db->query("DELETE FROM `message` WHERE `uin` = {$uin} AND `id` = {$id}");
		
		return $success ? 0 : 402;
	}
}


# end of script
